<?php
namespace app\shop\home;

use app\shop\model\Artwork;
use app\shop\model\Auction as AuctionModel;
use app\shop\model\ArtworkLog;
use app\admin\model\Attachment;
use app\shop\model\User;
use app\shop\model\AuctionOrder;
/** 
 * 前台首页控制器
 */
class Auction extends Common
{
    public function grouplist()
    {

        $active = AuctionModel::order('sort')->with('getimgpath')->select();

        $this->assign('active', $active);

        if(isMobile()){
            return $this->fetch('Mobile/Auction/grouplist');
        }else{
            return $this->fetch();
        }
    }

    public function group()
    {
        switch (input('get.order')) {
            case '2':
                $order = 'create_time asc';
                break;
            case '3':
                $order = 'auction_price desc';
                break;
            default:
                $order = 'create_time';
                break;
        }

        $active = AuctionModel::with(['getimgpath'])->where('id', request()->param('id'))->find();

        $artwork = Artwork::where('auction_id',$active['id'])->with('getartist')->order($order)->select();


       // var_dump($artwork);die;
        $this->assign('active', $active);

        $this->assign('artwork', $artwork);


        if(isMobile()){
            return $this->fetch('Mobile/Auction/group');
        }else{
            return $this->fetch();
        }
    }

    public function auctionLog()
    {   
        $id = request()->param('artwork_id');
        $price = request()->param('price');
        $user_id = session("auction_user")['id'];
        $userInfo = User::where('id',$user_id)->find()->toArray();
        $yuer = $price/10;
        if($yuer > $userInfo['money']){
            echo json_encode(['code'=>1,'msg'=>'余额不足应付金额的10%，请先去充值']);exit;
        }
        $ArtworkLog = ArtworkLog::where('artwork_id',$id)->field('price')->order('id desc')->find();
        if($price < $ArtworkLog['price']){
            echo json_encode(['code'=>1,'msg'=>'出价小于当前价格']);exit;
        }
        $data['artwork_id'] = $id;
        $data['user_id']    = $user_id;
        $data['price']      = $price;
        $data['status']     = 1;
        $data['create_time'] = time();
        $data['update_time'] = time();
        $res = ArtworkLog::insertGetId($data);
        if($res){
            echo json_encode(['code'=>0,'msg'=>'出价成功']);exit;
        }else{
            echo json_encode(['code'=>2,'msg'=>'系统错误，出价失败']);exit;
        }

    }

    public function auctionOrder(){
        //获取到时间的且未售出的拍卖品
        $artwork = Artwork::field('id,endtime')->where('type','neq',1)->where('sale_out',0)->select();
        $artworkEnd = [];
        foreach ($artwork as $k => $v) {
            if(strtotime($v['endtime']) < time()){
                $artworkEnd[] = $v->toArray();
            }
        }
        //获取拍卖品的ID集合
        $ids = array_column($artworkEnd, 'id');
        //根据产品ID查询拍卖日志
        $ArtworkLog = ArtworkLog::where('artwork_id','in',$ids)->select();
        foreach($ArtworkLog as $k1 => $v1){
            $ArtworkLog[$k1] = $v1->toArray();
        }
        //获取以产品ID为键名的日志数组
        $ArtworLogList = array_column($ArtworkLog,null, 'artwork_id');
        //获取日志的产品ID
        $ArtworIds = array_column($ArtworkLog,'artwork_id');
        //获取拍卖日志的UserID
        $userIds = array_column($ArtworLogList, 'user_id');
        //查询用户余额
        $userInfo = User::where('id','in',$userIds)->column('id,money');
        //拍卖订单数组重组
        $auctionOrder = [];
        foreach($ArtworLogList as $k2=>$v2){
            $auctionOrder[$k2]['order_num']=date('Ymd').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $auctionOrder[$k2]['artwork_id'] = $v2['artwork_id'];
            $auctionOrder[$k2]['artwork_log_id'] = $v2['id'];
            $auctionOrder[$k2]['price'] = $v2['price'];
            $auctionOrder[$k2]['user_id'] = $v2['user_id'];
            $auctionOrder[$k2]['create_time'] = time();
            $auctionOrder[$k2]['update_time'] = time();
            $yuer = $v2['price']/10;
            //余额够10%扣除余额不够则不扣除 状态记为0
            if($yuer > $userInfo[$v2['user_id']]){
                $auctionOrder[$k2]['real_price'] = 0;
                $auctionOrder[$k2]['status'] = 0;  //未扣余额
            }else{
                $auctionOrder[$k2]['real_price'] = $yuer;
                $auctionOrder[$k2]['status'] = 1;
            }
            //重新计算用户余额
            $userInfo[$v2['user_id']] = $userInfo[$v2['user_id']]-$auctionOrder[$k2]['real_price'];
           
        }
        //重组User数组
        $userData = [];
        foreach($userInfo as $k3=>$v3){
            $userData[$k3]['id'] = $k3;
            $userData[$k3]['money'] = $v3;
            $userData[$k3]['update_time'] = time();
        }
        $userData = array_values($userData);
        //开始事务
        User::startTrans();
        //插入拍卖订单
        $auctionOrderObj = new AuctionOrder;
        $res = $auctionOrderObj->saveAll($auctionOrder,false);
        if($res) {
            User::rollback();
            exit;
        }
        //改产品状态为以售出
        $res2 = Artwork::where('id', 'in', $ArtworIds)->where('sale_out', 0)->setInc('sale_out');
        if (!$res2) {
            User::rollback();
            exit;
        }
        $userObj = new User;
        $res3 = $userObj->saveAll($userData);
        if (!$res3) {
            User::rollback();
            exit;
        }
        User::commit();
        exit;
    }
}